import {useCallback, useEffect, useState} from 'react'
import Tabs from "../../components/tabs";
import InfiniteScroll from "../../components/infiniteScoll";
import moreImg from "./images/more.png"
import empty from "./images/empty.png"
import './index.scss'
import CONFIG from "./config.json"
import RuleModal from "./rule";

const {
  timeStr = '',
  firstTab = [],
  secondTab = [],
  thirdTab = [],
} = CONFIG

const data = Array(30).fill({
  url: `//randomuser.me/api/portraits/men/${Math.floor(Math.random() * 100)}.jpg`,
  name: 'sfsdfwcsscdcwefwcwe'
})
const SLICE = 10

function MidFestival() {
  const [showMore, setShowMore] = useState(true)
  const [ruleVisible, setRuleVisible] = useState(false)
  const [sliceIndex, setSliceIndex] = useState(SLICE)
  const [isOver, setIsOver] = useState(false)
  const [isStart, setIsStart] = useState(true)

  const [activeTab1, setActiveTab1] = useState(firstTab[0])
  const [activeTab2, setActiveTab2] = useState(secondTab[0])
  const [activeTab3, setActiveTab3] = useState(thirdTab[0])
  const [tab3Visible, setTab3Visible] = useState(false)

  useEffect(() => {
    setTab3Visible(activeTab1.tab !== 2 && activeTab2.tab === 0)
  }, [activeTab1.tab, activeTab2.tab])


  useEffect(() => {
    let nowTime = Date.now()
    let {timeStart, timeEnd} = activeTab3

    const startTime = new Date(timeStart).getTime()
    const endTime = new Date(timeEnd).getTime()
    setIsStart(nowTime >= startTime)
    setIsOver(nowTime >= endTime)

    if (nowTime >= startTime && nowTime <= endTime) {
      thirdTab.splice(activeTab3.tab, 1, {...activeTab3, name: 'Today'})
    }

  }, [activeTab3.tab, tab3Visible])

  const handleTab1Change = d => {
    setActiveTab1(d)
    setSliceIndex(SLICE)
  }

  const handleTab2Change = d => {
    setActiveTab2(d)
    setSliceIndex(SLICE)
  }

  const handleTab3Change = d => {
    setActiveTab3(d)
    setSliceIndex(SLICE)
  }


  const toPreTab = i => {
    setActiveTab3({...thirdTab[i - 1]})
  }

  const toNextTab = i => {
    setActiveTab3({...thirdTab[i + 1]})
  }

  const toRule = () => {
    setRuleVisible(true)
  }
  const toTask = () => {
    window.location.href = "/layout/mid-festival/task"
  }

  const loadData = () => {
    setTimeout(() => {
      setSliceIndex(d => d + SLICE)
    }, 500)
  }

  useEffect(() => {
    setShowMore(sliceIndex < data.length)
  }, [sliceIndex, data.length])

  const renderItem = useCallback((d, i) => {
    const tab = activeTab1.tab
    const isUnion = tab === 2

    return (
      <div className="normal-item">
        <div className="rank-num">
          {i + 1 <= 3 ? '' : (i + 1).toString().padStart(2, '0')}
        </div>
        <div className="user-info">
          {!isUnion && <div className="avatar">
            <img src={d.url} alt=""/>
          </div>}
          <div className="top-info">
            <p className="name">{d.name}</p>
            {(tab === 0 || isUnion) && (
              <div className="top-wrap">
                <p className="top">{isUnion ? `PK Point 9999999999999` : 'Top penjapa '}</p>
                {!isUnion && <div className="avatar">
                  <img src={`//randomuser.me/api/portraits/men/${Math.floor(Math.random() * 100)}.jpg`} alt=""/>
                </div>}
              </div>
            )}
          </div>
        </div>

        {isUnion ? (
          <div className="host">
            {Array(3).fill({}).map(d => <div className="avatar">
                <img src={`//randomuser.me/api/portraits/men/${Math.floor(Math.random() * 100)}.jpg`} alt=""/>
              </div>
            )}
          </div>
        ) : (
          <div className="num">
            999999
          </div>
        )}
      </div>
    )
  }, [activeTab1.tab, activeTab2.tab])

  const renderLoading = useCallback(() => (
    <div className="more">
      <img src={moreImg} alt=""/>
      <span>loading</span>
    </div>
  ), [])

  const renderFooter = useCallback(() => {
    const tab = activeTab1.tab
    if (tab === 2) {
      return null
    }
    return (
      (
        <li className="item item-rank item-self">
          <div className="normal-item">
            <div className="rank-num">
              99+
            </div>
            <div className="user-info">
              <div className="avatar">
                <img src={`//randomuser.me/api/portraits/women/${Math.floor(Math.random() * 100)}.jpg`} alt=""/>
              </div>
              <div className="top-info">
                <p className="name">hello world</p>
                {tab === 0 && (
                  <div className="top-wrap">
                    <p className="top">Top penjapa</p>
                    <div className="avatar">
                      <img src={`//randomuser.me/api/portraits/men/${Math.floor(Math.random() * 100)}.jpg`} alt=""/>
                    </div>
                  </div>
                )}
              </div>
            </div>
            <div className="num">
              999999
            </div>
          </div>
        </li>
      )
    )
  }, [activeTab1.tab])

  const renderEmpty = useCallback((text) => (
    <div className="empty">
      <img src={empty} alt=""/>
      {!!text && <p>No data</p>}
    </div>
  ), [])

  return (
    <div className={`MidYearFestival first-tab-${activeTab1.tab}`}>
      <button className="rule-btn" onClick={toRule}/>

      <p className="time-msg">{timeStr}</p>

      <Tabs activeKey={activeTab1.tab} data={firstTab} onChange={handleTab1Change} className="first-tab"/>
      {activeTab1.tab !== 2 &&
      <Tabs activeKey={activeTab2.tab} data={secondTab} onChange={handleTab2Change} className="second-tab"/>}
      <main>
        {activeTab1.tab !== 2 && activeTab2.tab === 0 && (<button className="task-btn" onClick={toTask}/>)}
        {tab3Visible && (
          <div className="arr-wrap">
            <button onClick={toPreTab.bind(null, activeTab3.tab)} className="arr arr-pre"
                    disabled={activeTab3.tab === 0}/>
            <button onClick={toNextTab.bind(null, activeTab3.tab)} className="arr arr-next"
                    disabled={activeTab3.tab === thirdTab.length - 1}/>
          </div>
        )}
        {tab3Visible && (
          <div className="third-tab-wrap">
            <Tabs
              activeKey={activeTab3.tab}
              data={thirdTab}
              onChange={handleTab3Change}
              className="third-tab"
              style={{
                transform: `translateX(${-4 * activeTab3.tab}%)`
              }}
            />
          </div>
        )
        }

        {
          activeTab1.tab === 2 && (
            <div className="tab3-title">
              Total
            </div>
          )
        }

        <div className="list-title">
          <p>Peringkat</p>
          <p>{['Host & Penjaga', 'Spender', 'Agency / Point'][activeTab1.tab]}</p>
          <p>{['Point', 'Point', 'Host'][activeTab1.tab]}</p>
        </div>

        {data.length < 1 ?
          renderEmpty()
          : (
            <InfiniteScroll
              className={`rank-list rank-list-${activeTab1.tab}`}
              data={data.slice(0, sliceIndex)}
              renderItem={renderItem}
              itemClassName={"item item-rank"}
              loadData={loadData}
              more={showMore}
              renderLoading={renderLoading}
              renderFooter={renderFooter}
            />
          )
        }
      </main>

      <div className="bg-bottom"/>

      <RuleModal
        closePlacement = "bottom"
        closable
        visible={ruleVisible}
        onClose={setRuleVisible.bind(null, false)}
      />
    </div>
  )
}

export default MidFestival
